package com.fll.codeworld.comment;

import com.fll.codeworld.annotation.WrapResp;
import com.fll.codeworld.model.Resp;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author fll
 * @description
 * @date 2021/11/4 16:05
 */

@ControllerAdvice(basePackages = {"com.fll.codeworld.controller"})
public class WrapRespAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        boolean wrap = methodParameter.hasMethodAnnotation(WrapResp.class);
        if (!wrap) {
            WrapResp annotation = methodParameter.getMethod() == null ? null : methodParameter.getMethod().getDeclaringClass().getAnnotation(WrapResp.class);
            if (annotation != null) {
                wrap = true;
            }
        }
        return wrap;
    }

    @Override
    public Object beforeBodyWrite(Object resp, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return Resp.builder().code("200").msg("success").data(resp).build();
    }
}
